import React,{Component} from 'react'
import * as pub from '../../config/public';
import{formatTimestamp} from '../../config/public';
import * as fetch from '../../config/fetch';
import $ from 'jquery'
import { message,Spin } from 'antd';
import {browserHistory} from 'react-router'
import { DatePicker } from 'antd';
import moment from 'moment';

const dateFormat = 'YYYY-MM-DD HH:mm:ss';
class SingleQuestion extends Component {
	constructor(args) {
		super();
	}
	delThis(number){
		$('#SingleQuestion' + number).remove();
	}
	numberInputs=(e)=>{
		let value=e.target.value;
		e.target.value=value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'');
	}
	render(){
		return(
			<div className="topic-cont SingleQuestion" id={'SingleQuestion' + this.props.number}>
				<h5><label>
				题目</label>
				<input required="required" className="question" type="text"  onKeyUp={this.numberInputs}/><a className='delete-question' onClick={()=>this.delThis(this.props.number)}><i className='icon-trash'></i></a></h5>
				<dl className="clearFix mar-t-20">
					<dt>选项</dt>
					<dd>
						<ul>
							<li><label>A</label><input required="required" className="describeA" type="text"/></li>
							<li><label>B</label><input required="required" className="describeB" type="text"/></li>
							<li><label>C</label><input required="required" className="describeC" type="text"/></li>
							<li><label>D</label><input required="required" className="describeD" type="text"/></li>
						</ul>
					</dd>
				</dl>
				<dl className="clearFix mar-t-20">
					<dt>答案</dt>
					<dd><label>
					<input  required="required" type="radio" name={'single_answer'+this.props.number}/>A</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>B</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>C</label><label>
					<input  type="radio" name={'single_answer'+this.props.number}/>D</label></dd>
				</dl>
			</div>
			)
	}
}
class MultipleQuestion extends Component {
	constructor(args) {
		super();
	}
	delThis(number){
		$('#MultipleQuestion' + number).remove();
	}
	numberInputs=(e)=>{
		let value=e.target.value;
		e.target.value=value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'');
	}
	render(){
		return(
			<div  className="topic-cont MultipleQuestion" id={'MultipleQuestion' + this.props.number}>
				<h5><label>
				题目</label>
				<input required="required" className="question" type="text" onKeyUp={this.numberInputs}/><a className='delete-question' onClick={()=>this.delThis(this.props.number)}><i className='icon-trash'></i></a></h5>
				<dl className="clearFix mar-t-20">
					<dt>选项</dt>
					<dd>
						<ul>
							<li><label>A</label><input required="required" className="describeA" type="text"/></li>
							<li><label>B</label><input required="required" className="describeB" type="text"/></li>
							<li><label>C</label><input required="required" className="describeC" type="text"/></li>
							<li><label>D</label><input required="required" className="describeD" type="text"/></li>
						</ul>
					</dd>
				</dl>
				<dl className="clearFix mar-t-20">
					<dt>答案</dt>
					<dd><label>
					<input type="checkbox"/>A</label><label>
					<input type="checkbox"/>B</label><label>
					<input type="checkbox"/>C</label><label>
					<input type="checkbox"/>D</label></dd>
				</dl>
			</div>
			)
	}
}
class AddForm extends Component {
	constructor(args) {
		super()
		this.state = {
			singleNum: 0,
			multipleNum: 0,
			loading: false,
			question: {
				testpaperTitle: '',
				examStartTime: '',
				examEndTime: '',
				titleSum: '',
				testScores: '',
				passLine: ''
			}
		}
	}
	addSingle() {
		this.setState({
			singleNum: this.state.singleNum + 1
		})
	}
	addMultiple() {
		this.setState({
			multipleNum: this.state.multipleNum + 1
		})
	}
	add(e) {
		e.preventDefault();
		let SingleQuestion = [];
		let MultipleQuestion = [];
		$('.SingleQuestion').each(function(i) {
			let question = $(this).find('.question').val();
			let describeA = $(this).find('.describeA').val();
			let describeB = $(this).find('.describeB').val();
			let describeC = $(this).find('.describeC').val();
			let describeD = $(this).find('.describeD').val();
			let checkboxList = $(this).find("input[type='radio']");
			let answer = 0;
			checkboxList.each((index, el) => {
				if (el.checked) {
					switch (index) {
						case 0:
							answer += 1;
							break;
						case 1:
							answer += 2;
							break;
						case 2:
							answer += 4;
							break;
						case 3:
							answer += 8;
							break;
						default:
							break;
					}
				}
			})
			SingleQuestion.push({
				question,
				describeA,
				describeB,
				describeC,
				describeD,
				answer
			})
		})
		$('.MultipleQuestion').each(function(i) {
			let question = $(this).find('.question').val();
			let describeA = $(this).find('.describeA').val();
			let describeB = $(this).find('.describeB').val();
			let describeC = $(this).find('.describeC').val();
			let describeD = $(this).find('.describeD').val();
			let checkboxList = $(this).find("input[type='checkbox']");
			let answer = 0;
			checkboxList.each((index, el) => {
				if (el.checked) {
					switch (index) {
						case 0:
							answer += 1;
							break;
						case 1:
							answer += 2;
							break;
						case 2:
							answer += 4;
							break;
						case 3:
							answer += 8;
							break;
						default:
							break;
					}
				}
			})
			MultipleQuestion.push({
				question,
				describeA,
				describeB,
				describeC,
				describeD,
				answer
			})
		})
		let flag = false;
		for (let x of MultipleQuestion) {
			if (x.answer.length === 0) {
				flag = true;
				break;
			}
		}
		if (flag) {
			message.error('多选题中有答案未选择', 1);
			return;
		}
		let newDate =  formatTimestamp(new Date(),'y-m-d')
		if(this.refs.examStartTime.value < newDate){
			message.error('开始时间不能小于当前时间', 3);
			return;
		}
		if(this.refs.examStartTime.value > this.refs.examEndTime.value){
			message.error('开始时间应小于结束时间', 1);
			return;
		}
		
		let testPaperData = {};
		let checkboxTitles = [];
		let radioTitles = [];

		for(let x in this.refs){
			testPaperData[x] = this.refs[x].value
		}
		testPaperData.testpaperId = this.props.testpaperId;

		for (let x of SingleQuestion) {
			radioTitles.push({
				radioTitle: x.question,
				radioAnswerDesc: [x.describeA, x.describeB, x.describeC, x.describeD],
				radioAnswer: x.answer,
				radioTitleType: 1
			});
		}
		for (let x of MultipleQuestion) {
			checkboxTitles.push({
				checkboxTitle: x.question,
				checkboxAnswerDesc: [x.describeA, x.describeB, x.describeC, x.describeD],
				checkboxAnswer: x.answer,
				checkboxTitleType: 2
			});
		}
		
		let formData = new FormData()
		formData.append('testPaperData', JSON.stringify(testPaperData));
		formData.append('radioTitles', JSON.stringify(radioTitles));
		formData.append('checkboxTitles', JSON.stringify(checkboxTitles));
		if(this.refs.examStartTime.value === undefined || this.refs.examEndTime.value === undefined){
			message.error('请选择考试时间', 3);
			return;
		}
		
		pub.loading(this,true);  
		fetch.editQuestion(formData).then((data) => {
			if (data.result === 'RC100') {
				message.success('编辑成功', 3);
				pub.jumpHistory.push('/admin/QuestionManage');
			} else {
				message.error(data.errMsg, 3);
			}
			pub.loading(this, false);

		}, (res) => {
			pub.reject(res);
			pub.loading(this, false);
		})

}
	numberInputs=(e)=>{
		let value=e.target.value;
		e.target.value=value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'');
	}
	numberValue=(e)=>{
		let value=e.target.value;
		e.target.value=value.replace(/[^\d]/g,'');;
	}
	componentDidMount() {
		$('#question_channel').find("option").eq(Number(pub.user.channelId)).attr("selected", true);
	}
	componentWillMount() {
		fetch.questionDetail(this.props.testpaperId).then((data) => {
			let radio = [],
				checkbox = [];
			for (let x of data.titleList) {
				if (x.titleType === '1') {
					radio.push(x)
				} else {
					checkbox.push(x)
				}
			}
		let question = data.testpaperData;
		let examStartTime = new Date(question.examStartTime.slice(0, 19));
		examStartTime = moment(examStartTime, dateFormat);
		let examEndTime = new Date(question.examEndTime.slice(0, 19));
		examEndTime = moment(examEndTime, dateFormat);
			this.setState({
				question,
				radio,
				checkbox,
				singleNum: radio.length,
				multipleNum: checkbox.length,
				examStartTime,
				examEndTime
			}, () => {
				this.defaultValue();
				this.refs.examStartTime.value = question.examStartTime.slice(0, 19);
				this.refs.examEndTime.value = question.examEndTime.slice(0, 19);

				$('.SingleQuestion').each(function(i) {
					let answer = pub.getAnswer(radio[i].answer);
					$(this).find('.question')[0].value = radio[i].title;
					$(this).find('.describeA')[0].value = radio[i].A;
					$(this).find('.describeB')[0].value = radio[i].B;
					$(this).find('.describeC')[0].value = radio[i].C;
					$(this).find('.describeD')[0].value = radio[i].D;
					$(this).find("input[type='radio']").each((index, el) => {
						for (let x of answer) {
							if (x === index) {
								el.checked = true;
							}
						}
					})

				})
				$('.MultipleQuestion').each(function(i) {
					let answer = pub.getAnswer(checkbox[i].answer);
					$(this).find('.question')[0].value = radio[i].title;
					$(this).find('.describeA')[0].value = radio[i].A;
					$(this).find('.describeB')[0].value = radio[i].B;
					$(this).find('.describeC')[0].value = radio[i].C;
					$(this).find('.describeD')[0].value = radio[i].D;
					$(this).find("input[type='checkbox']").each((index, el) => {
						for (let x of answer) {
							if (x === index) {
								el.checked = true;
							}
						}
					})

				})

			})
		}, (response) => {
			pub.reject(response);
		})
	}
	defaultValue(){
		let question = this.state.question;
		this.refs.testpaperTitle.value = question.testpaperTitle;
		this.refs.answerTime.value = question.answerTime;
		this.refs.passLine.value = question.passLine;
		this.refs.testScores.value = question.testScores;
	}
	render(){
		return(
				<Spin spinning={this.state.loading} tip="发布中...">
					<form onSubmit={(e)=>this.add(e)} className="topic-box tab">
						<ul className="que-inp">
							<li><label><span>考卷标题</span><input ref="testpaperTitle" required="required" type="text" onKeyUp={this.numberInputs}/></label></li>
							<li><label><span>考试时间</span>
							<DatePicker className='date_picker' value={this.state.examStartTime}  ref='examStartTime' showTime format={dateFormat} onChange={(date, dateString)=>{this.setState({examStartTime:date});this.refs.examStartTime.value=dateString;}}  />
							<font className="line-1"></font>
							<DatePicker className='date_picker' value={this.state.examEndTime}  ref="examEndTime" showTime format={dateFormat} onChange={(date, dateString)=>{this.setState({examEndTime:date});this.refs.examEndTime.value=dateString;}} />
							</label>
							</li>
							<li><label><span>答题时间</span><input ref="answerTime" required="required" type="text" className="minute" onKeyUp={this.numberValue}/>分钟</label></li>
							<li><label><span>渠道范围</span>
								<select ref='channel' disabled="disabled" id='question_channel'>
								     {pub.courseChannel.map((type,index)=>{
					     		     return(
					     		     	<option key={index} value={index}>{type}</option>
					     		     	)
					     	            })}
								</select>
							</label></li>
							<li><label><span>及格条件</span><input ref="passLine" required="required" type="text" className="minute" onKeyUp={this.numberValue}/></label></li>
							<li><label><span>考卷总分</span><input ref="testScores" required="required" type="text" className="minute" onKeyUp={this.numberValue}/>分</label></li>
						</ul>

				    <div className="topic-inp mar-t-20">
						<h4>单项选择题：</h4>
						
						{pub.getObject(this.state.singleNum).map((item,index)=>{
							return(
								  	<SingleQuestion key={index} number={index + 1}/>
								)
						})}

					<a className="add-topic" onClick={()=>this.addSingle()}>
					  <i className="icon-plus-sign-alt"></i>新增一题(单选)
					</a>

                   </div>


					<div className="topic-inp">
						<h4>多项选择题：</h4>
						{pub.getObject(this.state.multipleNum).map((item,index)=>{
							return(
								  	<MultipleQuestion key={index} number={index + 1}/>
								)
						})}
						<a className="add-topic" onClick={()=>this.addMultiple()}>
						  <i className="icon-plus-sign-alt"></i>新增一题(多选)
						</a>
					</div>

						<div className="row submit-btn mar-b-20 mar-t-20 text-center">
							<button type='submit' className="btn btn-blue">完成</button>
						</div>

					</form>
					</Spin>
		
			)
	}
}
class EditQuestion extends Component {
	constructor(args) {
		super()
		this.state = {
			tab: 1,
		}

	}

	render() {
		return (
			<div className="container">
				<div className="filter clearFix">
					<ul className="filter-ul nav clearFix">
						<li className={this.state.tab===1?"active":""} onClick={()=>{this.setState({tab:1})}}><a>编辑考题</a></li>
					</ul>
				</div>
				<div className="row bg-FFFFFF box-shadow">
				<AddForm testpaperId={this.props.params.id} />
				</div>
			</div>

		)
	}

}
export default EditQuestion

